<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="检测站名称" prop="staName" label-width="100px">
        <el-input v-model="queryParams.staName" placeholder="请输入检测站名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="检测站类型" prop="staType" label-width="100px">
        <el-select v-model="queryParams.staType" clearable placeholder="请选择检测站类型" @change="handleQuery"
          style="width: 240px">
          <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属企业" prop="enterpriseID" label-width="100px">
        <el-select v-model="queryParams.enterpriseID" clearable placeholder="请选择所属企业" @change="handleQuery"
          style="width: 240px">
          <el-option v-for="item in options2" :key="item.id" :label="item.entName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:role:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:role:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:role:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="roleList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="监测站名称"  v-if="columns[0].visible" prop="staName" align="center" width="200" />
      <el-table-column label="所属企业"  v-if="columns[1].visible" prop="enterpriseName" align="center" width="300" />
      <el-table-column label="所在地区"  v-if="columns[2].visible" prop="staAddr" :show-overflow-tooltip="false" align="center" width="200" />
      <el-table-column label="经度"   v-if="columns[3].visible" prop="longitude" />
      <el-table-column label="纬度"  v-if="columns[4].visible" prop="latitude" />
      <el-table-column label="监测站类型"  v-if="columns[5].visible" align="center" prop="stationName" width="150">
        <template #default="scope">
          <span>{{ options1.find(item => item.id == scope.row.staType)?.name || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="母线数量"  v-if="columns[6].visible" align="center" prop="masterCount" width="100"></el-table-column>
      <el-table-column label="支线数量"  v-if="columns[7].visible" align="center" prop="branchCount" width="100"></el-table-column>
      <el-table-column label="设备数量"  v-if="columns[8].visible" align="center" prop="deviceCount" width="100"></el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="300px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View"  @click="handleTonav(scope.row)">总览</el-button>
          <el-button link type="primary" icon="Guide" @click="handleTonavLine(scope.row)">线路管理</el-button>
          <el-button link type="primary" icon="Edit"  @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger"  icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属企业" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" placeholder="请选择所属企业">
            <el-option v-for="item in options2" :key="item.id" :label="item.entName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="站点名称" prop="staName">
          <el-input v-model.trim="form.staName" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="监测站地址" prop="staAddr">
          <el-input v-model="form.staAddr" type="textarea" :maxlength="100" placeholder="请输入监测站地址" style="width: 370px" />
          <el-button type="primary" @click="openMapPicker" style="margin-left: 10px">地图选点</el-button>
        </el-form-item>
      </el-form>
      <el-form-item label="监测站类型" label-width="100">
        <el-radio-group v-model="form.staType">
          <el-radio :value="1">列表站</el-radio>
          <el-radio :value="2">线路站</el-radio>
          <el-radio :value="3">实验站</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="站点状态" label-width="100">
        <el-radio-group v-model="form.state">
          <el-radio :value="1">正常使用</el-radio>
          <el-radio :value="0">已停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <AMapPointPickerInDialog ref="mapPickerDialogRef" @confirm="handleConfirm" />
    <!-- <MessagePopup ref="messagePopupRef" :show="hasNewMessage" @close="hasNewMessage = false" /> -->
  </div>
</template>

<script setup>
import { GetTenantPageList, AddTenant, EditTenant, DelTenant } from "@/api/system/tenant";
import { useInfoStore } from '@/store/modules/info.js'
import { useWebSocket } from '@/utils/useWebSocket.js'; //引入自定义的 WebSocket 钩子函数
import MessagePopup from '@/components/MessagePopup';//消息弹窗
import AMapPointPickerInDialog from '@/components/Amap/AMapPointPickerInDialog.vue';

const userInfo = useInfoStore();
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");
const router = useRouter();
const { proxy } = getCurrentInstance();
const mapPickerDialogRef = ref(null); //地图示例

// // 配置 WebSocket 连接地址（需替换为实际地址）
// const wsUrl = 'ws://www.icloudsafety.com/dianli/stationMonitorWs/100219';
// // 初始化 WebSocket 实例
// const {
//   isConnected,
//   hasNewMessage,
//   sendMessage,
//   on,
//   destroy,
//   initWebSocket
// } = useWebSocket(wsUrl, {
//   reconnectTimes: 3, // 自定义重连次数
//   heartbeatInterval: 15000 // 自定义心跳间隔
// });
// const messagePopupRef = ref(null);

// // 订阅自定义消息事件
// on('onMessage', (msg) => {
//   if (messagePopupRef.value) {
//     const mockEvent = { data: msg };
//     messagePopupRef.value.handleMessage(mockEvent);
//   }
// });

// // 组件挂载时初始化连接
// onMounted(() => {
//   initWebSocket();
// });

// // 组件卸载时销毁连接
// onBeforeUnmount(() => {
//   destroy();
// });

const roleList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);
const options1 = ref([
  { id: '1', name: '列表站' },
  { id: '2', name: '线路站' },
  { id: '3', name: '实验站' },
]);
const options2 = ref([]);
const data = reactive({
  form: {
    id: null,
    enterpriseID: null,
    staName:  null,
    longitude:  null,
    latitude:  null,
    staAddr:  null,
    geoAddr:  null,
    geoCode:  null,
    staType: 1,
    state: 1
  },
  queryParams: {
    pageNo : 1,
    pageSize: 10,
    enterpriseID:null,
    staName:null,
    staAddr:null,
    state:null,
    staType:null,
  },
  rules: {
    enterpriseID: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    staName: [{ required: true, message: "站点名称不能为空", trigger: "blur" }],
  },
});

// 列显隐信息
const columns = ref([
  { key: 0, label: `监测站名称`, visible: true },
  { key: 1, label: `所属企业`, visible: true },
  { key: 2, label: `所在地区`, visible: true },
  { key: 3, label: `经度`, visible: true },
  { key: 4, label: `纬度`, visible: true },
  { key: 5, label: `监测站类型`, visible: true },
  { key: 6, label: `母线数量`, visible: true },
  { key: 7, label: `支线数量`, visible: true },
  { key: 8, label: `设备数量`, visible: true },
]);

const { queryParams, form, rules } = toRefs(data);

// 地图选点信息
function handleConfirm(point) {
  console.log("🚀 ~ handleConfirm ~ point:", point)
  
  if(point){
    form.value.longitude = point.longitude;
    form.value.latitude = point.latitude;
    form.value.staAddr = point.name;
    form.value.geoCode = point.adcode;
    form.value.geoAddr = point.fullAddress;
  }
 
}
/** 查询企业列表下拉 */
function getGetEnterpriseList() {
  proxy.cloudTv_API.GetEnterpriseList({}).then(response => {
    if (response.data) {
      options2.value = response.data || [];
    }
  });
}
/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetStationPageList(queryParams.value).then(response => {
    roleList.value = response.data.list;
    total.value = response.data.total || 0;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除监测站"' + row.staName + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelStation({ id: row.id }).then(response => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}


/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    id: null,
    enterpriseID: null,
    staName:  null,
    longitude:  null,
    latitude:  null,
    staAddr:  null,
    geoAddr:  null,
    geoCode:  null,
    staType: 1,
    state: 1
  };
  proxy.resetForm("roleRef");
}

/** 总览跳转 */
function handleTonav(row) {
 // staType // 1 列表站 2 线路站 3 实验站
  let { id, enterpriseID, staType ,staCode  } = row;
  router.push(`/public/cloudTv/dataView?id=${id}&entId=${enterpriseID}&staCode=${staCode}`)
  // if (staType === 2) {
  //   router.push(`/public/cloudTv/dataView?id=${id}&entId=${enterpriseID}`)
  // }else if (staType === 3) {
  //   router.push(`/public/cloudTv/e800tDataView?id=${id}&entId=${enterpriseID}`)
  // }
}
// 支线管理
function handleTonavLine(row) {
  let { id, enterpriseID } = row;
  router.push(`/public/cloudTv/lineControl?id=${id}&enterpriseID=${enterpriseID}`)
}

/** 添加 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}

/** 修改 */
// 在 handleUpdate 方法中
function handleUpdate(row) {
  reset();
  // 填充表单数据
  Object.keys(form.value).forEach(key => {
    form.value[key] = row[key];
    if (form.value[key] == undefined) {
      form.value[key] = null
    }
  });
  open.value = true;
  title.value = "修改";
}

// 打开地图选点
function openMapPicker() {
  if (mapPickerDialogRef.value) {
    // 如果有经纬度，解析并传入
    let position = null;
    if (form.value.lngLat) {
      const [lng, lat] = form.value.lngLat.split(',');
      if (lng && lat) {
        position = { lng: parseFloat(lng), lat: parseFloat(lat) };
      }
    }
    mapPickerDialogRef.value.openDialog(position);
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.EditStation({
          ...form.value,
          uniqueKey: userInfo.info.uniqueKey
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddStation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 复制
async function copy(text) {
  console.log(text);
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);

  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
getGetEnterpriseList();
getList();
</script>
